import sys
from PySide6.QtWidgets import QApplication
from login import LoginWindow, read_login_data
from control import ControlWindow

def main():
	app = QApplication(sys.argv)
	login_window = LoginWindow()
	control_window = ControlWindow()

	def on_login_success():
		login_window.close()
		control_window.show()

	def on_logout():
		control_window.close()
		# 清空登录框内容
		login_window.ui.plainTextEdit.setPlainText("")
		login_window.ui.plainTextEdit_2.setPlainText("")
		login_window.show()

	# monkey patch: 在login成功时调用on_login_success
	def patched_login():
		username = login_window.ui.plainTextEdit.toPlainText().strip()
		password = login_window.ui.plainTextEdit_2.toPlainText().strip()
		data = read_login_data()
		from PySide6.QtWidgets import QMessageBox
		if not data:
			QMessageBox.warning(login_window, "登录失败", "未注册用户，请先注册！")
			return
		if username == data.get("username") and password == data.get("password"):
			QMessageBox.information(login_window, "登录成功", f"欢迎，{username}！")
			on_login_success()
		else:
			QMessageBox.critical(login_window, "登录失败", "用户名或密码错误！")
	login_window.login = patched_login

	# 绑定control界面的退出登录按钮
	# pushButton_5 是退出登录按钮
	control_window.ui.pushButton_5.clicked.connect(on_logout)

	login_window.show()
	sys.exit(app.exec())

if __name__ == "__main__":
	main()
